import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Switch,
  Alert,
  ActivityIndicator,
  Dimensions
} from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { 
  setInterval,
  setSpeed,
  setCurrentPlatform,
  selectSettings,
  selectIsAutoScrolling,
  selectCurrentPlatform
} from '../../store/slices/autoScrollSlice';
import PlatformAdapter from '../../services/platformAdapter';
import PermissionManager from '../../services/permissionManager';
import statisticsService from '../../services/statistics';

const { width: screenWidth } = Dimensions.get('window');

const HomeScreen = () => {
  const dispatch = useDispatch();
  const settings = useSelector(selectSettings);
  const isAutoScrolling = useSelector(selectIsAutoScrolling);
  const currentPlatform = useSelector(selectCurrentPlatform);
  
  const [platforms, setPlatforms] = useState([]);
  const [loading, setLoading] = useState(true);
  const [permissions, setPermissions] = useState({});
  const [stats, setStats] = useState(null);

  useEffect(() => {
    initializeData();
  }, []);

  // 初始化数据
  const initializeData = async () => {
    try {
      setLoading(true);
      
      // 初始化统计服务
      await statisticsService.initialize();
      
      // 检查权限
      const permissionResults = await PermissionManager.checkAllPermissions();
      setPermissions(permissionResults);
      
      // 检测已安装的平台
      const installedPlatforms = await PlatformAdapter.detectInstalledPlatforms();
      setPlatforms(installedPlatforms);
      
      // 获取统计数据
      const usageStats = statisticsService.getUsageReport();
      setStats(usageStats);
      
      console.log('首页数据初始化完成');
    } catch (error) {
      console.error('初始化数据失败:', error);
      Alert.alert('错误', '初始化数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理权限请求
  const handlePermissionRequest = async () => {
    try {
      const results = await PermissionManager.requestAllPermissions();
      setPermissions(results);
      
      const allGranted = PermissionManager.areAllPermissionsGranted(results);
      if (!allGranted) {
        const missingPermissions = PermissionManager.getMissingPermissions(results);
        Alert.alert(
          '权限不足',
          `需要以下权限才能正常运行：\n${missingPermissions.join('\n')}`,
          [
            { text: '取消', style: 'cancel' },
            { text: '去设置', onPress: () => PermissionManager.openAppSettings() }
          ]
        );
      }
    } catch (error) {
      console.error('请求权限失败:', error);
      Alert.alert('错误', '请求权限失败');
    }
  };

  // 处理平台选择
  const handlePlatformChange = (platform) => {
    dispatch(setCurrentPlatform(platform));
  };

  // 处理间隔设置
  const handleIntervalChange = (value) => {
    dispatch(setInterval(value));
  };

  // 处理速度设置
  const handleSpeedChange = (value) => {
    dispatch(setSpeed(value));
  };

  // 检查权限状态
  const checkPermissionStatus = (permission) => {
    return permissions[permission] === 'granted';
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4CAF50" />
        <Text style={styles.loadingText}>正在初始化...</Text>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>自动下滑翻视频</Text>
        <Text style={styles.subtitle}>智能视频浏览助手</Text>
      </View>

      {/* 权限状态 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>权限状态</Text>
        <View style={styles.permissionContainer}>
          <View style={styles.permissionItem}>
            <Text style={styles.permissionText}>无障碍服务</Text>
            <View style={[
              styles.permissionIndicator,
              checkPermissionStatus('accessibility') ? styles.permissionGranted : styles.permissionDenied
            ]} />
          </View>
          <View style={styles.permissionItem}>
            <Text style={styles.permissionText}>悬浮窗权限</Text>
            <View style={[
              styles.permissionIndicator,
              checkPermissionStatus('android.permission.SYSTEM_ALERT_WINDOW') ? styles.permissionGranted : styles.permissionDenied
            ]} />
          </View>
          <View style={styles.permissionItem}>
            <Text style={styles.permissionText}>存储权限</Text>
            <View style={[
              styles.permissionIndicator,
              checkPermissionStatus('android.permission.WRITE_EXTERNAL_STORAGE') ? styles.permissionGranted : styles.permissionDenied
            ]} />
          </View>
        </View>
        {!PermissionManager.areAllPermissionsGranted(permissions) && (
          <TouchableOpacity style={styles.permissionButton} onPress={handlePermissionRequest}>
            <Text style={styles.permissionButtonText}>请求权限</Text>
          </TouchableOpacity>
        )}
      </View>

      {/* 平台选择 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>选择平台</Text>
        <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.platformContainer}>
          {platforms.map((platform) => (
            <TouchableOpacity
              key={platform.key}
              style={[
                styles.platformItem,
                currentPlatform === platform.key && styles.platformItemSelected
              ]}
              onPress={() => handlePlatformChange(platform.key)}
            >
              <Text style={[
                styles.platformIcon,
                currentPlatform === platform.key && styles.platformIconSelected
              ]}>
                {platform.key === 'douyin' && '🎵'}
                {platform.key === 'kuaishou' && '📱'}
                {platform.key === 'xigua' && '🍉'}
                {platform.key === 'bilibili' && '📺'}
                {platform.key === 'weishi' && '⏱️'}
                {platform.key === 'local' && '📁'}
              </Text>
              <Text style={[
                styles.platformName,
                currentPlatform === platform.key && styles.platformNameSelected
              ]}>
                {platform.name}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>

      {/* 设置选项 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>滑动设置</Text>
        
        {/* 间隔设置 */}
        <View style={styles.settingItem}>
          <Text style={styles.settingLabel}>滑动间隔</Text>
          <View style={styles.settingControls}>
            <TouchableOpacity
              style={styles.controlButton}
              onPress={() => handleIntervalChange(Math.max(1, settings.interval - 1))}
            >
              <Text style={styles.controlButtonText}>-</Text>
            </TouchableOpacity>
            <Text style={styles.settingValue}>{settings.interval}秒</Text>
            <TouchableOpacity
              style={styles.controlButton}
              onPress={() => handleIntervalChange(Math.min(30, settings.interval + 1))}
            >
              <Text style={styles.controlButtonText}>+</Text>
            </TouchableOpacity>
          </View>
        </View>

        {/* 速度设置 */}
        <View style={styles.settingItem}>
          <Text style={styles.settingLabel}>滑动速度</Text>
          <View style={styles.speedOptions}>
            {['slow', 'normal', 'fast'].map((speed) => (
              <TouchableOpacity
                key={speed}
                style={[
                  styles.speedOption,
                  settings.speed === speed && styles.speedOptionSelected
                ]}
                onPress={() => handleSpeedChange(speed)}
              >
                <Text style={[
                  styles.speedText,
                  settings.speed === speed && styles.speedTextSelected
                ]}>
                  {speed === 'slow' && '慢'}
                  {speed === 'normal' && '中'}
                  {speed === 'fast' && '快'}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </View>

      {/* 使用统计 */}
      {stats && (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>使用统计</Text>
          <View style={styles.statsContainer}>
            <View style={styles.statItem}>
              <Text style={styles.statLabel}>总滑动次数</Text>
              <Text style={styles.statValue}>{stats.summary.totalScrolls}</Text>
            </View>
            <View style={styles.statItem}>
              <Text style={styles.statLabel}>总使用时间</Text>
              <Text style={styles.statValue}>{formatTime(stats.summary.totalTime)}</Text>
            </View>
            <View style={styles.statItem}>
              <Text style={styles.statLabel}>平均速度</Text>
              <Text style={styles.statValue}>
                {stats.summary.averageScrollsPerMinute}次/分钟
              </Text>
            </View>
          </View>
        </View>
      )}

      {/* 操作提示 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>操作提示</Text>
        <View style={styles.tipsContainer}>
          <Text style={styles.tipText}>• 点击悬浮按钮开始/暂停自动滑动</Text>
          <Text style={styles.tipText}>• 长按悬浮按钮停止自动滑动</Text>
          <Text style={styles.tipText}>• 拖拽悬浮按钮可改变位置</Text>
          <Text style={styles.tipText}>• 确保已授予所有必要权限</Text>
        </View>
      </View>
    </ScrollView>
  );
};

// 格式化时间
const formatTime = (milliseconds) => {
  const seconds = Math.floor(milliseconds / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  
  if (hours > 0) {
    return `${hours}小时${minutes % 60}分钟`;
  } else if (minutes > 0) {
    return `${minutes}分钟${seconds % 60}秒`;
  } else {
    return `${seconds}秒`;
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5F5F5',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  header: {
    backgroundColor: '#4CAF50',
    padding: 24,
    paddingTop: 40,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#FFFFFF',
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: '#E8F5E8',
  },
  section: {
    backgroundColor: '#FFFFFF',
    marginHorizontal: 16,
    marginVertical: 8,
    borderRadius: 12,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  permissionContainer: {
    marginBottom: 12,
  },
  permissionItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  permissionText: {
    fontSize: 14,
    color: '#666',
  },
  permissionIndicator: {
    width: 12,
    height: 12,
    borderRadius: 6,
  },
  permissionGranted: {
    backgroundColor: '#4CAF50',
  },
  permissionDenied: {
    backgroundColor: '#FF4444',
  },
  permissionButton: {
    backgroundColor: '#FF9800',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 8,
    alignItems: 'center',
  },
  permissionButtonText: {
    color: '#FFFFFF',
    fontSize: 14,
    fontWeight: 'bold',
  },
  platformContainer: {
    flexDirection: 'row',
  },
  platformItem: {
    backgroundColor: '#F5F5F5',
    padding: 12,
    borderRadius: 8,
    marginRight: 8,
    alignItems: 'center',
    minWidth: 80,
  },
  platformItemSelected: {
    backgroundColor: '#4CAF50',
  },
  platformIcon: {
    fontSize: 24,
    marginBottom: 4,
  },
  platformIconSelected: {
    color: '#FFFFFF',
  },
  platformName: {
    fontSize: 12,
    color: '#666',
    textAlign: 'center',
  },
  platformNameSelected: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#F0F0F0',
  },
  settingLabel: {
    fontSize: 14,
    color: '#333',
    fontWeight: '500',
  },
  settingControls: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  controlButton: {
    backgroundColor: '#4CAF50',
    width: 32,
    height: 32,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 8,
  },
  controlButtonText: {
    color: '#FFFFFF',
    fontSize: 18,
    fontWeight: 'bold',
  },
  settingValue: {
    fontSize: 14,
    color: '#666',
    minWidth: 60,
    textAlign: 'center',
  },
  speedOptions: {
    flexDirection: 'row',
  },
  speedOption: {
    backgroundColor: '#F5F5F5',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 16,
    marginHorizontal: 4,
  },
  speedOptionSelected: {
    backgroundColor: '#4CAF50',
  },
  speedText: {
    fontSize: 14,
    color: '#666',
  },
  speedTextSelected: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  statsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  statItem: {
    alignItems: 'center',
  },
  statLabel: {
    fontSize: 12,
    color: '#666',
    marginBottom: 4,
  },
  statValue: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  tipsContainer: {
    backgroundColor: '#F9F9F9',
    padding: 12,
    borderRadius: 8,
  },
  tipText: {
    fontSize: 12,
    color: '#666',
    marginBottom: 4,
    lineHeight: 18,
  },
});

export default HomeScreen;